import isType from './isType'
class PartServer {
  constructor() {
    this.allComps = {}
    this.currentRoutePath = null
    this.vue_root = null
  }
  init(t) {
    this.vue_root = t
  }
  getCurrentContext() {
    return this.vue_root
  }
  getCompByTagName(t) {
    if (!t) return void console.warn('1 argument required, but only 0 present.')
    if (!this.getCurrentContext()) return void console.warn('root do not exist')
    this._getCurrentAllComps()
    let e = []
    if (
      0 !=
      (e = this.allComps[this.currentRoutePath].filter(
        e => e.$options._componentTag === t
      )).length
    )
      return e
    console.warn(`Components labeled ${t} do not exist`)
  }
  getCompById(id) {
    if (!id)
      return void console.warn('1 argument required, but only 0 present.')
    if (!this.getCurrentContext()) return void console.warn('root do not exist')
    this._getCurrentAllComps()
    let e = []
    if (
      0 !=
      (e = this.allComps[this.currentRoutePath].filter(e => e.$el.id === id))
        .length
    )
      return e[0]
    console.warn(`Components with ID name ${t} do not exist`)
  }
  _getAllChildComp(t) {
    let e
    let i = []
    isType.isObject(t) ? (e = t.$children) : isType.isArray(t) && (e = t)
    for (let t = 0; t < e.length; t++) {
      i.push(e[t])
      if (e[t].$children.length > 0) {
        i = i.concat(this._getAllChildComp(e[t].$children))
      }
    }
    return i
  }
  _getCurrentAllComps() {
    let t = this.getCurrentContext()
    this.currentRoutePath = this.vue_root.$router.currentRoute.path
    this.allComps[this.currentRoutePath] = this._getAllChildComp(t)
  }
}

const partServer = new PartServer()

export default partServer
